package com.mysiteforme.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.base.BaseController;
import com.mysiteforme.admin.entity.Dict;
import com.mysiteforme.admin.util.Constants;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;

/**
 * Created by wangl on 2018/1/1.
 * todo:
 */
@Controller
@RequestMapping("admin/electricityUserSetting")
public class ElectricityUserSettingController extends BaseController{
    private static final Log log = LogFactory.get();


    @GetMapping("list")
    @SysLog("跳转系统字典页面")
    public String list(){
        return "admin/electricityUserSetting/list";
    }

    @PostMapping("list")
    @ResponseBody
    public LayerData<Dict> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                ServletRequest request){
        LayerData<Dict> layerData = new LayerData<>();
        EntityWrapper<Dict> wrapper = new EntityWrapper<>();
        wrapper.eq("type", Constants.electricity_user_setting).or().eq("type", Constants.electricity_small_user)
                .or().eq("type", Constants.electricity_big_user);
        wrapper.eq("del_flag",false);
        Page<Dict> dataPage = dictService.selectPage(new Page<>(page,limit),wrapper);
        layerData.setCount(dataPage.getTotal());
        layerData.setData(dataPage.getRecords());
        return layerData;
    }

    @GetMapping("edit")
    public String edit(Long id,Model model){
        Dict dict = dictService.selectById(id);
        model.addAttribute("dict",dict);
        return "admin/electricityUserSetting/edit";
    }

    @PostMapping("edit")
    @SysLog("编辑系统字典")
    @ResponseBody
    public RestResponse edit(Dict dict){
        if(dict.getId()==null || dict.getId() == 0){
            return RestResponse.failure("字典ID不能为空");
        }
        if(StringUtils.isBlank(dict.getLabel())){
            return RestResponse.failure("字典标签不能为空");
        }
        if(StringUtils.isBlank(dict.getValue())){
            return RestResponse.failure("字典标签对应的值不能为空");
        }
        dictService.saveOrUpdateDict(dict);
        return RestResponse.success();
    }
}
